package com.example.iitematicviewer.api.author;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.iitematicviewer.util.SnowFlakeGenerateIdWorker;
import com.example.iitematicviewer.vo.AuthorVO;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AuthorTransService {

    /**
     * 新增将JSON转换实体类方法
     * @return
     */
    public AuthorVO transJsonBySave(JSONObject param){
        AuthorVO authorVO = new AuthorVO();
        SnowFlakeGenerateIdWorker snowFlakeGenerateIdWorker = new SnowFlakeGenerateIdWorker(0L,0L);
        //主键
        String id = snowFlakeGenerateIdWorker.generateNextId();
        authorVO.setId(id);
        //UID
        String uid = snowFlakeGenerateIdWorker.generateNextId().substring(0,8);
        authorVO.setUid(uid);
        //名称
        String authorName = param.getString(AuthorConstant.authorName);
        if (StringUtils.isNotEmpty(authorName)) {
            authorVO.setAuthorName(authorName);
        }
        //个人链接
        String spacelink = param.getString(AuthorConstant.spacelink);
        if (StringUtils.isNotEmpty(spacelink)) {
            authorVO.setSpacelink(spacelink);
        }
        //注册时间
        String nowDate = getNowDate();
        if (StringUtils.isNotEmpty(nowDate)) {
            authorVO.setCreateTime(nowDate);
        }
        //修改时间
        String updateTime = getNowDate();
        if (StringUtils.isNotEmpty(updateTime)) {
            authorVO.setUpdateTime(updateTime);
        }
        return authorVO;
    }

    /**
     * 单个查询转换为JSON
     * @param authorVO
     * @return
     */
    public JSONObject tranAuthorByJSON(AuthorVO authorVO){
        JSONObject obj = new JSONObject();
        obj.put("author",authorVO);
        return obj;
    }

    /**
     * 修改将实体转换为实体
     * @param authorVO
     * @param param
     * @return
     */
    public AuthorVO transJsonByUpdate(JSONObject param,AuthorVO authorVO){
        //作者名称
        String authorName = param.getString(AuthorConstant.authorName);
        authorVO.setAuthorName(authorName);
        //个人连接
        String spacelink = param.getString(AuthorConstant.spacelink);
        if (StringUtils.isNotEmpty(spacelink)) {
            authorVO.setSpacelink(spacelink);
        }
        else{
            authorVO.setSpacelink(null);
        }
        //修改时间
        authorVO.setUpdateTime(getNowDate());
        return authorVO;
    }

    /**
     * 获取当前时间
     * @return
     */
    private String getNowDate(){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd : hh:mm:ss");
        return dateFormat.format(date);
    }

}
